/**
 * 
 */
package org.dragonfire.dasm.preprocessor.blockDefs;

import org.dragonfire.dasm.Command;
import org.dragonfire.dasm.CompileException;
import org.dragonfire.dasm.preprocessor.Block;
import org.dragonfire.dasm.preprocessor.BlockDef;
import org.dragonfire.dasm.preprocessor.Preprocessor;

/**
 * @author Darth Android
 * @date Sep 8, 2007
 */
public class LoopBlockDef extends BlockDef {

	@Override
	public Block createBlock(Preprocessor prep, Command c) {
		LoopBlock lb = new LoopBlock(prep);
		return lb;
	}

	public class LoopBlock extends Block {

		private String conditional;
		private String updateCmd;
		private int startLine = -1;
		private String startFile;

		public LoopBlock(Preprocessor prep) {
			super("loop", "endloop", new String[0]);
			startFile = prep.getCurrentFileName();
			startLine = prep.getCurrentLineNum();
		}

		@Override
		public void parsePersonalDirective(Preprocessor prep, Command c) {
			String name = c.getName();
			if (name.equalsIgnoreCase("endfor") || name.equalsIgnoreCase("endwhile")
					|| name.equalsIgnoreCase("endrepeat")) {
				if (prep.getCompiler().evalBool(conditional)) {
					// run the command, but don't let it return any Listings
					if (updateCmd != null)
						prep.preprocessLine(updateCmd);
					if (!prep.getCurrentFileName().equals(startFile)) {
						throw new CompileException("ERROR_LOOP_WRONG_FILE", startFile, startLine - 1);
					}
					prep.getCurrentFile().lineNum = startLine;
				}
				else {
					prep.popBlock();
					prep.setParsing(true);
				}
			}
			else if (name.equalsIgnoreCase("while")) {
				conditional = c.getParam(0);
				if (!prep.getCompiler().evalBool(conditional)) {
					prep.setParsing(false);
				}
			}
			else if (name.equalsIgnoreCase("repeat")) {
				conditional = c.getParam(0);
			}
			else if (name.equalsIgnoreCase("loop")) {
				conditional = c.getParam(0);
				updateCmd = c.getParam(1);
			}
			else
				super.parsePersonalDirective(prep, c);
		}
	}
}
